package DDL;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import DuiXiang.TableModel;

/**
 * @author 胡伟强
 *
 */
public class EditTable {
	@SuppressWarnings("finally")
	public static boolean editTable(String dataBaseName, String tableName,
			TableModel tableModel) {
		File tableFile = new File("D:\\database\\" + dataBaseName + "\\"
				+ tableName + ".dbf");
		if (!tableFile.exists()) {
			System.out.println("没有这张表");
			return false;
		}
		FileReader fileReader = null;
		BufferedReader bufferReader = null;
		List<String> tempStringArray = new ArrayList<String>();
		try {
			fileReader = new FileReader(tableFile);
			bufferReader = new BufferedReader(fileReader);
			String tempString = null;
			try {
				String[] tempStringList;
				while ((tempString = bufferReader.readLine()) != null) {
					tempStringList = tempString.split(",");// 按逗号分隔到数组tempStringList
					if (tempStringList[0].equals(tableModel.getsFieldName())) {// 找到要修改的那一行
						tempString = tableModel.getsFieldName() + ","
								+ tableModel.getsType() + ","
								+ tableModel.getiSize() + ","
								+ tableModel.getbKey() + ","
								+ tableModel.getbNullFlag() + ","
								+ tableModel.getbValidFlag();
					}
					tempStringArray.add(tempString);
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return false;
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		} finally {
			try {
				bufferReader.close();
				fileReader.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		FileWriter fileWriter = null;
		BufferedWriter bufferWriter = null;
		try {
			fileWriter = new FileWriter(tableFile);
			bufferWriter = new BufferedWriter(fileWriter);
			Iterator<String> iterator = tempStringArray.iterator();
			while (iterator.hasNext()) {
				bufferWriter.write(iterator.next());
				bufferWriter.newLine();
			}
			bufferWriter.flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		} finally {
			try {
				bufferWriter.close();
				fileWriter.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return true;
		}
	}
}
